package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-01-03
 */
@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {

    @Override
    public Integer getEntryByUserIdOrEquipmentId(Integer userId, String equipmentId) {
//        这里的实体有可能是user也可以是设备  当用户id=0 就是设备
        LambdaQueryWrapper<ApBehaviorEntry> queryWrapper = new LambdaQueryWrapper<>();
        if(userId==0){  //就是设备
            queryWrapper.eq(ApBehaviorEntry::getEntryId,equipmentId);
            ApBehaviorEntry one = this.getOne(queryWrapper);
            if(one==null){
                one = new ApBehaviorEntry();
                one.setType(0);
                one.setEntryId(equipmentId);
                one.setCreatedTime(new Date());
                this.save(one);
            }
            return one.getId();
        }else{  //就是用户
            queryWrapper.eq(ApBehaviorEntry::getEntryId,userId.toString());
            ApBehaviorEntry one = this.getOne(queryWrapper);
            if(one==null){
                one = new ApBehaviorEntry();
                one.setType(1);
                one.setEntryId(userId.toString());
                one.setCreatedTime(new Date());
                this.save(one);
            }
            return one.getId();
        }
    }
}
